/*
 * DeleteProductServlet.java
 * 作用：管理员后台的商品删除控制器，负责处理删除指定商品的请求。
 */
package com.campustradingwall.controller.admin;

import com.campustradingwall.dao.ProductDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admin/deleteProduct")
public class DeleteProductServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String productIdStr = request.getParameter("productId");

        if (productIdStr == null) {
            session.setAttribute("message", "无效的操作请求，缺少商品ID。");
            response.sendRedirect(request.getContextPath() + "/admin/products");
            return;
        }

        try {
            int productId = Integer.parseInt(productIdStr);
            ProductDao productDao = new ProductDao();
            productDao.deleteProduct(productId);
            session.setAttribute("message", "商品已成功删除。");

        } catch (NumberFormatException e) {
            session.setAttribute("message", "无效的商品ID格式。");
        } catch (Exception e) {
            session.setAttribute("message", "删除商品时发生错误：" + e.getMessage());
            e.printStackTrace();
        }

        response.sendRedirect(request.getContextPath() + "/admin/products");
    }
} 